import os
import sys

sys.path.insert(0, "./python")
from common import AuthInfo

import requests


class GetMachinesInfo:
    def __init__(self, maas_url, session, zone):
        self.maas_url = maas_url.rstrip("/") + "/"
        self.session = session
        self.zone = zone
        self.results = self._get_hosts_info()

    def _get_hosts_info(self):
        url = f"{self.maas_url}api/2.0/machines/?zone={self.zone}"
        resp = self.session.get(url)
        resp.raise_for_status()
        machines = resp.json()
        results = []
        for m in machines:
            results.append({
                "hostname": m.get("hostname"),
                "system_id": m.get("system_id"),
                "status": m.get("status_name"),
                "boot_disk": (m.get("boot_disk") or {}).get("name"),
                "power_type": m.get("power_type", ""),
            })
        self._get_power_info(results)
        return results

    def _get_power_info(self, data):
        for host in data:
            url = f"{self.maas_url}api/2.0/machines/{host.get('system_id')}/op-power_parameters"
            resp = self.session.get(url)
            resp.raise_for_status()
            power_info = resp.json()
            host["power_user"] = power_info.get("power_user")
            host["power_address"] = power_info.get("power_address")
            host["power_pass"] = power_info.get("power_pass")

    def format_hosts_info(self):
        if self.results is None:
            return None
        else:
            headers = [("hostname", "hostname"),
                       ("system_id", "system_id"),
                       ("status", "status"),
                       ("boot_disk", "boot_disk"),
                       ("power_type", "power_type"),
                       ("power_user", "power_user"),
                       ("power_address", "power_address"),
                       ("power_pass", "power_pass")]
            col_widths = [max(len(str(row[key])) for row in self.results) for _, key in headers]
            col_widths = [max(w, len(h)) for w, (h, _) in zip(col_widths, headers)]
            header_line = " | ".join(h.ljust(w) for (h, _), w in zip(headers, col_widths))
            separator = "-+-".join("-" * w for w in col_widths)
            lines = []
            for row in self.results:
                line = " | ".join(str(row.get(key, "")).ljust(w) for (_, key), w in zip(headers, col_widths))
                lines.append(line)
            return "\n".join([header_line, separator] + lines)


if __name__ == "__main__":
    zone = sys.argv[1].split("=", 1)[1] if sys.argv[1].startswith("zone=") else sys.argv[1]
    maas_url = os.getenv("maas_url")
    api_key = os.getenv("api_key")

    auth = AuthInfo(maas_url, api_key)
    client = GetMachinesInfo(auth.maas_url, auth.session, zone)
    print(client.format_hosts_info())
